package com.ang.juc.n4.t2;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Test2 {

    private int number = 1; //标志位 1:A 2:B 3:C

    private Lock lock  = new ReentrantLock();

    private Condition condition1 = lock.newCondition();

    private Condition condition2 = lock.newCondition();

    private Condition condition3 = lock.newCondition();

    public void print5(){//打印5次是A的工作

        lock.lock();

        try {
            //1.判断
            while(number!=1){ //标志位是1：A
                condition1.await();
            }

            //2.干活
            for (int i = 1; i <= 5; i++) {
                System.out.println(Thread.currentThread().getName()+"\t");
            }

            //3.通知
            number = 2;
            condition2.signalAll(); //要精确唤醒B进程 通过Number标志位实现

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }

    public void print10(){//打印5次是B的工作

        lock.lock();

        try {
            //1.判断
            while(number!=2){ //标志位是2:B
                condition2.await(); //不是B的话 就等待
            }

            //2.干活
            for (int i = 1; i <= 10; i++) {
                System.out.println(Thread.currentThread().getName()+"\t");
            }

            //3.通知
            number = 3;
            condition3.signalAll(); //要精确唤醒 C进程 通过Number标志位实现

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }

    public void print15(){//打印5次是C的工作

        lock.lock();

        try {
            //1.判断
            while(number!=3){ //标志位是3:C
                condition3.await();
            }

            //2.干活
            for (int i = 1; i <= 15; i++) {
                System.out.println(Thread.currentThread().getName()+"\t");
            }

            //3.通知
            number = 1;
            condition1.signalAll(); //要精确唤醒A进程 通过Number标志位实现

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }


    public static void main(String[] args) {
        Test2 shareResource = new Test2();

        new Thread(()->{

            for (int i = 1; i <= 10 ; i++) {
                shareResource.print5();
            }

        },"A").start();

        new Thread(()->{

            for (int i = 1; i <= 10 ; i++) {
                shareResource.print10();
            }

        },"B").start();

        new Thread(()->{

            for (int i = 1; i <= 10 ; i++) {
                shareResource.print15();
            }

        },"C").start();

    }

}
